$(function () {
    var isAjax = false;

    $("input,textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function ($form, event, errors) {
            // additional error messages or events
        },
        submitSuccess: function ($form, event) {
            event.preventDefault(); // prevent default submit behaviour
            // get values from FORM
            var name = $("input#user-name").val();
            var email = $("input#user-email").val();
            var product = $("input#user-product").val();
            var message = $("textarea#user-message").val();
            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            if (isAjax){
                return false;
            }
            isAjax = true
            $.ajaxSetup({headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}});

            $.ajax({
                url: "/message",
                type: "POST",
                dataType: 'json',
                data: {
                    name: firstName,
                    email: email,
                    product: product,
                    message: message
                },
                cache: false,
                success: function (data) {
                    if (data.code !== 0) {
                        // Fail message
                        isAjax = true;
                        $('#section-reply-form .invalid-feedback').css('display','block').html(data.msg)
                    } else {
                        isAjax = false;
                        window.location.href= '/leave-message-success';
                    }
                }
            })
        },
        filter: function () {
            return $(this).is(":visible");
        },
    });
});

